import { Component, OnInit } from '@angular/core';
import {Message, TreeNode} from 'primeng/primeng';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {DutyService} from '../duty.service';
import {ActivatedRoute, ParamMap, Router} from '@angular/router';
import {StorageService} from '../../services/storage.service';
import {environment} from '../../../environments/environment';
import {PublicService} from '../../services/public.service';


@Component({
  selector: 'app-schedule-edit',
  templateUrl: './schedule-edit.component.html',
  styleUrls: ['./schedule-edit.component.scss']
})
export class ScheduleEditComponent implements OnInit {
    currentSheduleId;                               // 当前路由的计划ID

    zh: any;                                        // 汉化
    beginTime: Date;                                // 开始时间
    endTime: Date;                                  // 结束时间
    beginTimeCalendar: Date;                        //

    shiftSearchOptions: any[];                      // 排班班次可选择的数据
    shiftSelectedMultipleOption: any[] = [];        // 排班班次已被选取的数据
    relativeSearchOptions: any[];                   // 关联计划可选择的数据
    relativeSelectedMultipleOption: any[] = [];     // 关联计划已被选择的数据
    approveSearchOptions: any[];                    // 审批人可以被选择的数据
    approveSelectedMultipleOption: any[] = [];      // 审批人已被选择的数据

    defaultId: string;                              // 新增排班编号
    defaultCreator: string;                         // 新增排班创建人
    defaultCreateTime: string;                      // 新增排班创建时间
    defaultStatus: string;                          // 计划状态

    departementDisplay: boolean;                    // 部门组织树显示控制
    selectedDepartment = '';                        // 表单显示的已选中的部门组织
    filesTree4: TreeNode[];                         // 部门组织初始
    selected: TreeNode[];                           // 部门组织结束
    selectedStr = '';                               // 部门选中的OID字符串

    msgs: Message[] = [];                           // 表单验证提示
    msgPop: Message[] = [];                         // 验证消息弹框提示
    hadSaved: boolean;                              // 保存是否成功
    hadDownload: boolean;                           // 生成排班表是否成功
    downloadBtn: boolean;                           // 导入按钮是否显示
    saved: boolean;                                 // 保存按钮是否显示

    uploadIp: string;                                // 上传接口
    progressBar: boolean;                            // 进度条

    newSchdule: FormGroup;
    formBuilder: FormBuilder = new FormBuilder();
    shiftValue = new FormControl([]);
    approvarValue = new FormControl([]);
    relativeValue = new FormControl([]);
    recivedAppDatas: any;                           // 存储审批人请求到的数据
    recicedShiftDatas: any;                         // 存储班次请求到的数据
    recivedRelaDatas: any;                          // 存储关联计划到的数据

    initOrg: any;                                   // 初始部门


    constructor(private dutyService: DutyService,
                private activitedRoute: ActivatedRoute,
                private storageService: StorageService,
                private publicService: PublicService,
                private router: Router) {
    }

    ngOnInit() {
        this.currentSheduleId = this.activitedRoute.snapshot.paramMap.get('id');
        this.uploadIp = `${environment.url.management}/onduty/upload`;
        this.createForm();
        this.initDatas();
        this.zh = this.initZh();
        this.initDepartmentDatas();
        this.departementDisplay = false;
        this.hadSaved = true;
        this.hadDownload = true;
        this.downloadBtn = false;
        this.progressBar = true;
        this.saved = false;
        this.selected = [];

    }
    initDatas() {
        this.beginTimeCalendar = new Date();
        this.dutyService.getScheduleById(this.currentSheduleId).subscribe(res => {
            this.defaultId = res.did;
            this.defaultCreator = res.creator;
            this.newSchdule.get('schduleName').setValue(res.name);
            this.defaultCreateTime = res.create_time;
            this.selectedDepartment = res.duty_org;
            this.defaultStatus = res.status;
            this.beginTime = res.begin_time;
            this.initOrg = res.orgs_structures;
            this.endTime = new Date(res.end_time);
            if (res['approver_structures']) {
                let initAppArray = [];
                this.recivedAppDatas = res['approver_structures'];
                for ( let val of res['approver_structures']) {
                    initAppArray.push(val['name']);
                }
                this.approvarValue.setValue(initAppArray);


            }
            if (res['shift_structures']) {
                let initShiftArray = [];
                this.recicedShiftDatas = res['shift_structures'];
                for ( let val of res['shift_structures']) {
                    initShiftArray.push(val['name']);
                }
                this.shiftValue.setValue(initShiftArray);
            }
            if (res['related_duty']) {
                let relatedArray = [];
                this.recivedRelaDatas = res['related_duty'];
                relatedArray.push(res['related_duty']);
                this.relativeValue.setValue(relatedArray);
            }


        });
    }
    initZh() {
        return {
            firstDayOfWeek: 1,
            dayNames: [ '周一', '周二', '周三', '周四', '周五', '周六', '周日' ],
            dayNamesShort: [ '一', '二', '三', '四', '五', '六', '七' ],
            dayNamesMin: [ '一', '二', '三', '四', '五', '六', '七' ],
            monthNames: [ '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月' ],
            monthNamesShort: [ '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二' ],
        };
    }
    initDepartmentDatas() {
        this.dutyService.getDepartmentDatas().subscribe(res => {
            this.filesTree4 = res;
        });
    }
    // 部门组织树模态框
    showTreeDialog() {
        this.departementDisplay = true;
    }
    // 组织树懒加载
    nodeExpand(event) {
        if (event.node) {
            this.dutyService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
                event.node.children  = res;
            });
        }
    }
    clearTreeDialog () {
        this.selectedDepartment = '';
        let query = '';
        this.publicService.getApprovers(this.selectedStr).subscribe(res => {
            this.approveSearchOptions =  this.approveSearchOptions = this.filterCountry(query, res);
        });
    }
    closeTreeDialog() {
        console.log(this.selected);
        this.initOrg = [];
        let selectedOid: Array<any> = [];
        let selectedName: Array<any> = [];
        let query = '';
        this.approveSelectedMultipleOption = [];
        // console.log(this.selected);
        for (let val of this.selected) {
            selectedOid.push(val['oid']);
            selectedName.push(val['label']);
        }
        this.selectedStr = selectedOid.join(',');
        this.selectedDepartment = selectedName.join(',');
        this.publicService.getApprovers(this.selectedStr).subscribe(res => {
            this.approveSearchOptions =  this.approveSearchOptions = this.filterCountry(query, res);
        });
        this.departementDisplay = false;
    }

    createForm() {
        this.newSchdule = this.formBuilder.group({
            schduleName: ['', Validators.required],
            scheduleApprovor: [this.approveSelectedMultipleOption, Validators.required],
            scheduleId: [this.defaultId, Validators.required],
            scheduleCreator: [this.defaultCreator, Validators.required],
            scheduleCreateTime: [this.defaultCreateTime, Validators.required],
            scheduleDepartment: ['', Validators.required],
            schduleStart: ['', Validators.required],
            schduleEnd: ['', Validators.required],
            schduleShift: ['', Validators.required],
            schduleRelative: ['', Validators.required]
        });
    }

    filterApproverMultiple(event) {
        let query = event.query;
        this.publicService.getApprovers(this.selectedStr).subscribe(res => {
            this.recivedAppDatas = res;
            this.approveSearchOptions = this.filterCountry(query, res);
        });
    }

    filterShiftMultipe(event) {
        let query = event.query;
        this.dutyService.getAllSchduleShifts().subscribe(res => {
            this.recicedShiftDatas = res;
            this.shiftSearchOptions = this.filterCountry(query, res) ;
        });
    }

    filterRelativeMutipe(event) {
        let query = event.query;
        this.dutyService.getRelaticeScheduleData().subscribe(res => {
            this.recivedRelaDatas = res;
            this.relativeSearchOptions = this.filterCountry(query, res);
        });
    }

    showError() {
        this.msgs = [];
        this.msgs.push({severity: 'error', summary: '错误消息提示', detail: '请填写完整表单'});
    }

    submit() {
        // console.log(this.approveSelectedMultipleOption);
        // console.log(this.recivedAppDatas);
        let approvePidArray = [];
        for ( let i = 0; i < this.approveSelectedMultipleOption.length; i++) {
            for ( let j = 0; j < this.recivedAppDatas.length; j++) {
                if (this.approveSelectedMultipleOption[i] === this.recivedAppDatas[j]['name']) {
                    approvePidArray.push(this.recivedAppDatas[j]);
                }
            }
        }
        // console.log(approvePidArray);
        // console.log(this.shiftSelectedMultipleOption);
        // console.log(this.recicedShiftDatas);
        let shiftsSidArray = [];
        for ( let i = 0; i < this.shiftSelectedMultipleOption.length; i++) {
            for ( let j = 0; j < this.recicedShiftDatas.length; j++) {
                if (this.shiftSelectedMultipleOption[i] === this.recicedShiftDatas[j]['name']) {
                    shiftsSidArray.push(this.recicedShiftDatas[j]);
                }
            }
        }
        // console.log(shiftsSidArray);
        // console.log(this.relativeSelectedMultipleOption);
        // console.log(this.recivedRelaDatas);
        let relativeDidStr = '';
        for ( let i = 0; i < this.relativeSelectedMultipleOption.length; i++) {
            for ( let j = 0; j < this.recivedRelaDatas.length; j++) {
                if (this.relativeSelectedMultipleOption[i] === this.recivedRelaDatas[j]['name']) {
                    relativeDidStr = this.recivedRelaDatas[j]['did'].toString();
                }
            }
        }
        // console.log(relativeDidStr);
        console.log(this.approveSelectedMultipleOption);
        let selectedArray = [];
        if (this.initOrg.length) {
            // console.log(this.initOrg);
            // console.log(23333);
             selectedArray = this.initOrg;
        }else {
            // console.log(this.selected);
            // console.log(55555);
            for ( let i = 0; i < this.selected.length; i++ ) {
                selectedArray[i] = {
                    oid: this.selected[i]['oid'],
                    name: this.selected[i]['label']
                };
            }
        }


        this.msgs = [];
        if ( (!this.defaultId)
            || (!this.defaultCreator)
            || (!this.newSchdule.get('schduleName').value)
            || !this.defaultCreateTime
            || !(String(this.approveSelectedMultipleOption))
            || !this.shiftSelectedMultipleOption
            || !this.selectedDepartment) {
                this.showError();
        }else if ( this.beginTime.toString() === this.endTime.toString()) {
            this.msgs = [];
            this.msgs.push({severity: 'error', summary: '错误消息提示', detail: '起始时间和结束时间不能相同'});
        } else {
            this.dutyService.editSchedule(
                this.defaultId,
                this.defaultCreator,
                this.newSchdule.get('schduleName').value,
                this.defaultCreateTime,
                selectedArray,
                approvePidArray,
                this.formatDate(this.beginTime),
                this.formatDate(this.endTime),
                shiftsSidArray,
                relativeDidStr,
                this.defaultStatus).subscribe(res => {
                    if ( res === '00000' ) {
                        this.msgPop = [];
                        this.hadSaved = false;
                        this.msgPop.push({severity: 'success', summary: '消息提示', detail: '计划保存成功'});
                        this.saved = true;
                    }else {
                        this.msgPop = [];
                        this.msgPop.push({severity: 'error', summary: '提示消息', detail: '计划保存失败' + '\n' + res });
                    }
            });
        }
    }

    formatDate(date) {
        if (/[0-9]{4}-[0-9]{2}-[0-9]{2}/.exec(date)) {
            return date;
        } else {
            let y = date.getFullYear();
            let m = date.getMonth() + 1;
            m = m < 10 ? '0' + m : m;
            let d = date.getDate();
            d = d < 10 ? ('0' + d) : d;
            return y + '-' + m + '-' + d;
        }

    }

    filterCountry(query, countries: any[]): any[] {
        let filtered: any[] = [];
        for (let i = 0; i < countries.length; i++) {
            let country = countries[i];
            if (country.name.toLowerCase().indexOf(query.toLowerCase()) === 0) {
                filtered.push(country.name);
            }
        }
        return filtered;
    }

    downloadModel() {
        this.progressBar = false;
        this.dutyService.downloadModel(this.defaultId).subscribe(res => {
            if (!res) {
                this.progressBar = true;
                this.msgPop = [];
                this.msgPop.push({severity: 'error', summary: ' 提示消息', detail: '模板生成失败' });
            }else {
                this.progressBar = true;
                this.msgPop = [];
                this.hadDownload = false;
                this.downloadBtn = true;
                window.open(`${environment.url.management}/${res}`, '_blank');
                this.msgPop.push({severity: 'success', summary: '消息提示', detail: '模板生成成功！请在本地文件夹中查看'});
            }
        });
    }

    onBeforeUpload(event) {
        let token = this.storageService.getToken('token');
        event.formData.append('access_token', token);
        event.formData.append('id', this.defaultId);
    }
    onUpload(event) {
        let res = JSON.parse(event.xhr.response);
        if ( res['errcode'] === '00000') {
            this.msgPop = [];
            this.msgPop.push({severity: 'success', summary: '消息提示', detail: '计划导入成功'});
            window.setTimeout(() => {
                this.router.navigateByUrl('index/duty/manage');
            }, 1100);
        }else {
            this.msgPop = [];
            this.msgPop.push({severity: 'error', summary: '提示消息', detail: '计划导入失败' + res['errmsg'] });
        }
    }
    showInputBtn() {
        this.hadDownload = false;
    }

    startTimeSelected(t) {
        this.endTime = t;
        // console.log( this.endTime);
    }
}
